package halberd.filter;

import halberd.DataType;
import halberd.ImgFilter;
import halberd.data.FlipType;
import halberd.data.ImgData;
import halberd.data.ImgDataFactory;

public class FlipFilter implements ImgFilter {
	private FlipType flipType;

	public FlipFilter(FlipType flipType) {
		this.flipType = flipType;
	}

	public ImgData process(ImgData input) {
		if (!canProcess(input)) {
			return null;
		}
		ImgData result = ImgDataFactory.createImgData(input.getWidth(), input.getHeight());
		flip(input.getDatas(), result.getDatas(), input.getWidth(), input.getHeight());
		result.setDataType(DataType.GRAY);
		return result;
	}

	private boolean canProcess(ImgData input) {
		if (input == null) {
			return false;
		}
		if (flipType == null) {
			return false;
		}
		return true;
	}

	private void flip(int[][][] src, int[][][] dst, int w, int h) {
		if (flipType == FlipType.LeftRight) {
			leftRightFlip(src, dst, w, h);
		} else if (flipType == FlipType.UpDown) {
			upDownFlip(src, dst, w, h);
		} else if (flipType == FlipType._360) {
			_360Flip(src, dst, w, h);
		}
	}

	private void leftRightFlip(int[][][] src, int[][][] dst, int w, int h) {
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				dst[i][j][0] = src[w - i][j][0];
				dst[i][j][1] = src[w - i][j][1];
				dst[i][j][2] = src[w - i][j][2];
				dst[i][j][3] = src[w - i][j][3];
				dst[i][j][4] = src[w - i][j][4];
			}
		}
	}

	private void upDownFlip(int[][][] src, int[][][] dst, int w, int h) {
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				dst[i][j][0] = src[i][h - j][0];
				dst[i][j][1] = src[i][h - j][1];
				dst[i][j][2] = src[i][h - j][2];
				dst[i][j][3] = src[i][h - j][3];
				dst[i][j][4] = src[i][h - j][4];
			}
		}
	}

	private void _360Flip(int[][][] src, int[][][] dst, int w, int h) {
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				dst[i][j][0] = src[w - i][h - j][0];
				dst[i][j][1] = src[w - i][h - j][1];
				dst[i][j][2] = src[w - i][h - j][2];
				dst[i][j][3] = src[w - i][h - j][3];
				dst[i][j][4] = src[w - i][h - j][4];
			}
		}
	}
}
